package com.github.carter659.spring04;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
/*import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;*/
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.mysql.jdbc.StringUtils;

@Controller
public class MainController {

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private TopicRespository topicRespository;
	@Autowired
	private ThemeRepositoy themeRepositoy;




	@Autowired
	private NewsRespository newsRespository;

	@GetMapping("/")
	public String index() {
		return "forward:/indexs.html";
	}

	@RequestMapping(value="/save",method =RequestMethod.POST )
	public @ResponseBody Map<String, Object> save(@RequestBody Order order) {
		Map<String, Object> result = new HashMap<>();
		if (StringUtils.isNullOrEmpty(order.id)){
			order.id = orderDao.insert(order);
		}else {
			orderDao.update(order);
		}
		result.put("id", order.id);
		return result;
	}

	@RequestMapping(value="/getArticle",method=RequestMethod.GET)
	public @ResponseBody Object get(@RequestParam Integer id) {
		return newsRespository.findOne( id );
	}

	@RequestMapping(value="/findAll", method=RequestMethod.GET)
	public @ResponseBody Object findAll(@RequestParam Integer perPage,@RequestParam Integer pageNum) {
		List<Map<String,Object>> result = topicRespository.findAll( perPage,pageNum );
		return result;

	}

	@RequestMapping(value="/findAllNews", method=RequestMethod.GET)
	public @ResponseBody Object findAllNews(@RequestParam Integer perPage,@RequestParam Integer pageNum,@RequestParam String topic) {
		 topic = topicRespository.findOne( topic );
		List<Map<String,Object>> result = newsRespository.findAll( perPage,pageNum ,topic);
       return result;
	}
	@RequestMapping(value="/findAllTopicByTag", method=RequestMethod.GET)
	public @ResponseBody Object findAllTopicByTag(@RequestParam Integer perPage,@RequestParam Integer pageNum,@RequestParam String tag) {

		List<Map<String,Object>> result = themeRepositoy.findAll( perPage,pageNum ,tag);
		return result;
	}
	@RequestMapping(value="/findAllTagByTopic", method=RequestMethod.GET)
	public @ResponseBody Object findAllTopicByTag(@RequestParam String topic) {

		List<String> result = themeRepositoy.findThemesByTopic( topic);
		return result;
	}

	@RequestMapping(value="/findArticleBySentenceId", method=RequestMethod.GET)
	public @ResponseBody Object findArticleBySentenceId(@RequestParam String sid) {

		List<Map<String,Object>> result = newsRespository.findArticleBySentenceId( sid );
		return result;
	}

	@PostMapping("/delete")
	public @ResponseBody Map<String, Object> delete(String id) {
		Map<String, Object> result = new HashMap<>();
		orderDao.delete(id);
		result.put("id", id);
		return result;
	}

}
